import { Controller, Get, Post, Body, Patch, Param, Delete, Res, Session, Req, } from '@nestjs/common';
import { UserService } from './user.service';
import type { User_add, Login, Update } from "../Types/User"
import { Config } from "../Config"
import * as md5 from "md5"
import * as svgCaptcha from "svg-captcha"


const pression = {
  BigAdmin: [{
    key: "screen",
    icon: "FileOutlined",
    label: "数据图表",
  },
  {
    key: "users",
    icon: "UserOutlined",
    label: "用户列表",
  },
  {
    key: "food",
    icon: "PieChartOutlined",
    label: "食谱",

  },
  {
    key: "discuss",
    icon: "CommentOutlined",
    label: "评论",

  }],
  Admin: [{
    key: "screen",
    icon: "FileOutlined",
    label: "数据图表",
  },

  {
    key: "food",
    icon: "PieChartOutlined",
    label: "食谱",

  }, {
    key: "discuss",
    icon: "CommentOutlined",
    label: "评论",

  }],
  commont: [
    {
      key: "screen",
      icon: "FileOutlined",
      label: "数据图表",
    }
  ]

}

@Controller('user')
export class UserController {
  constructor(private readonly userService: UserService) { }

  @Post()
  async create(@Body() body: User_add, @Res() res, @Session() session, @Req() req) {
    res.setHeader("Access-Control-Allow-Origin", "http://127.0.0.1:5173");
    res.setHeader("Access-Control-Allow-Methods", "POST, GET,OPTIONS,DELETE, HEAD,PUT");
    res.setHeader("Access-Control-Allow-Headers", "access-control-allow-origin, authority, content-type, version-info, X-Requested-With");
    res.setHeader("Access-Control-Allow-Credentials", "true")
    console.log(body, session.code, '注册')
    if (!session.code || session.code !== body.code) {
      res.status(422).send({
        message: '验证码错误'
      })
    } else {
      const result = await this.userService.create({ ...body, password: md5(body.password + Config.Script) })
      if (!result) {
        console.log(result)
        res.status(423).send({
          status: 423,
          message: "账号或qq已被使用"
        })
      } else {
        req.session.destroy(() => {
          res.clearCookie('delicious', { path: '/' });
          res.status(200).send({
            status: 200,
            message: "成功"
          })
        })
      }
    }


  }
  @Post('/login')
  async login(@Body() body: Login, @Res() res, @Session() session, @Req() req) {
    console.log(body, session.code, '登录')
    if (!session.code || session.code !== body.code) {
      res.status(422).send({
        message: '验证码错误'
      })
    } else {
      const { username, password } = body
      const result = await this.userService.login({ username, password: md5(password + Config.Script) })

      if (!result) {
        res.status(400).send({
          status: 400,
          message: "失败",
          data: {}
        })
      } else {
        req.session.userinfo = result
        req.session.isLogin = true
        res.status(200).send({
          status: 200,
          message: "成功",
          data: result
        })
      }

    }

  }
  @Post('/forget')
  async forget(@Body() body, @Res() res) {
    const { qqnumber } = body
    console.log(qqnumber)
    const result = await this.userService.forget({ qqnumber, password: md5('123456' + Config.Script) })
    console.log(result)
    if (!result) {
      res.status(424).send({
        status: 424,
        message: "不存在的qq",
        data: {}
      })
    } else {
      res.status(200).send({
        status: 200,
        message: "成功",
        data: {}
      })
    }

  }
  @Post('/update')
  async update(@Body() body: Update, @Res() res) {
    const { avatar, bilibili, brithday, constellation, description, sex, username, _id } = body
    const result: any = await this.userService.update(_id, { avatar, bilibili, brithday, constellation, description, sex, username })
    try {
      if (result.matchedCount == 0) {
        res.status(425).send({
          status: 425,
          message: "失败",
          data: {}
        })
      } else {
        res.status(200).send({
          status: 200,
          message: "成功",
          data: result
        })
      }
    } catch (error) {

    }
  }
  @Post('/loginout')
  async loginout(@Req() req, @Res() res) {
    req.session.destroy(() => {
      res.clearCookie('delicious', { path: '/' });
      res.status(200).send({
        status: 200,
        message: "退出成功"
      })
    })
  }
  @Get('code')
  Code(@Req() req, @Res() res, @Session() session) {
    const CodeImg = svgCaptcha.createMathExpr({
      mathMin: 1,
      mathMax: 10,
      mathOperator: '+',
      size: 4,
      fontSize: 50,
      color: true,
      background: 'orange',
      inverse: true,
      width: 100
    })

    session.code = CodeImg.text
    res.type('image/svg+xml')
    res.send(CodeImg.data)
  }

  @Post('/admin')

  async admin_log(@Body() body, @Res() res, @Session() Session, @Req() req) {
    const data = {
      user: {},
      pression: []
    }
    const { username, password } = body
    if (body.code === Session.code) {
      const result = await this.userService.login_admin({ username, password: md5(password + Config.Script) })
      console.log(result)
      if (!result) {
        res.status(400).send({
          status: 400,
          message: "用户名或密码错误"
        })
        return
      }
      data.user = result
      switch (result.role) {
        case '0':
          data.pression = pression.BigAdmin
          break;
        case '1':
          data.pression = pression.Admin
          break;
        case '2':
          data.pression = pression.commont
          break;
        default:
          break;
      }
      res.status(200).send({
        status: 200,
        data: data
      })
    } else {
      res.status(422).send({
        status: 422,
        message: "验证码错误"
      })
    }


  }

  @Post('/admin/updatepass')
  async admin_out(@Body() Body, @Res() res) {
    console.log(Body)
    const { password, oldpass } = Body
    const result = await this.userService.update_pass({ oldpassword: md5(oldpass + Config.Script), password: md5(password + Config.Script) })

    if (!result) {
      res.status(425).send({
        status: 425,
        message: "修改失败"
      })
    } else {
      console.log(result)
      if (result.matchedCount == 0) {
        res.status(425).send({
          status: 425,
          message: "修改失败"
        })
      } else {
        res.status(200).send({
          status: 200,
          message: "成功"
        })
      }

    }

  }

  @Post('/list/:page/:role')
  async findAll(@Body() Body, @Res() res, @Param() params) {
    console.log(Body)
    const { keyword } = Body
    const result: any = await this.userService.findAll(params.page, params.role, keyword)
    res.status(200).send({
      status: 200,
      data: result.data,
      count: result.count
    })

  }

  @Post('/admin/adduser')
  async admin_add(@Res() res, @Body() body) {
    const result = await this.userService.create({ ...body, password: md5(body.password + Config.Script) })
    if (!result) {
      res.status(423).send({
        status: 423,
        message: "账号或qq已被使用"
      })
    } else {
      res.status(200).send({
        status: 200,
        message: "成功"
      })
    }
  }

  @Post('/admin/role')
  async admin_role(@Res() res, @Body() body) {
    const { id, role } = body
    const result = await this.userService.updateRole(id, role)
    if (!result) {
      res.status(423).send({
        status: 423,
        message: "修改失败"
      })
    } else {
      res.status(200).send({
        status: 200,
        message: "成功"
      })
    }
  }
  @Delete()
  async deleteone(@Body() body, @Res() res) {
    const { id } = body
    const result = await this.userService.deleteOne(id)
    if (!result) {
      res.status(427).send({
        status: 427,
        message: '删除失败'
      })

    } else {
      if (result.deletedCount == 1) {
        res.status(200).send({
          status: 200,
          message: '成功'
        })
      } else {
        res.status(427).send({
          status: 427,
          message: '删除失败'
        })
      }

    }


  }
  @Get('/test')
  test(@Session() session) {
    console.log(session)
  }



}
